package cn.icanci.ladybird.service.user.impl;

import cn.icanci.ladybird.common.result.JsonData;
import cn.icanci.ladybird.common.util.cache.RedisUtils;
import cn.icanci.ladybird.common.util.common.CommonUtils;
import cn.icanci.ladybird.common.util.images.BaseHeadImagesUtils;
import cn.icanci.ladybird.common.util.security.JWTUtils;
import cn.icanci.ladybird.pojo.bo.UserLoginByCodeBO;
import cn.icanci.ladybird.pojo.bo.UserLoginByUsernameAndPasswordBO;
import cn.icanci.ladybird.pojo.bo.UserRegisterBO;
import cn.icanci.ladybird.pojo.bo.UserResetPwdBO;
import cn.icanci.ladybird.pojo.entity.UserInfo;
import cn.icanci.ladybird.service.UserInfoService;
import cn.icanci.ladybird.service.user.UserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author: icanci
 * @date: Created in 2020/10/14 14:01
 * @classAction: 处理用户登录注册的实现
 */
@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public String queryByUserLoginByUsernameAndPasswordBO(UserLoginByUsernameAndPasswordBO userLoginByUsernameAndPasswordBO) {
        if (null == userLoginByUsernameAndPasswordBO) {
            return null;
        }
        String account = userLoginByUsernameAndPasswordBO.getAccount();
        UserInfo userInfo = userInfoService.queryOneByUsername(account);
        String password = CommonUtils.MD5(userLoginByUsernameAndPasswordBO.getPassword());
        if (null == userInfo || !userInfo.getUserInfoPassword().equals(password)) {
            return null;
        }
        String token = JWTUtils.generateJWTWebToken(userInfo);
        return token;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonData userRegister(UserRegisterBO userRegisterBO) {
        if (!StringUtils.isBlank(userRegisterBO.getAccount())) {
            // 判断是否已经注册
            UserInfo userInfo = userInfoService.queryOneByUsername(userRegisterBO.getAccount());
            System.out.println(userInfo);
            if (userInfo != null) {
                return JsonData.builderError("用户已经注册，请登录或者找回密码");
            }
        }
        // 判断非空 非空格
        log.info("UserLoginServiceImpl.userRegister - " + getPassword(userRegisterBO));
        if (null == getPassword(userRegisterBO)) {
            return JsonData.builderError("用户密码不一致或者其他数据为空");
        }
        // 判断Code
        // 从Redis中获取数据
        String targetCode = (String) redisUtils.get(userRegisterBO.getAccount());
        log.info("UserLoginServiceImpl.userRegister - " + targetCode);
        if (!userRegisterBO.getCode().equals(targetCode)) {
            return JsonData.builderError("验证码错误或者已经失效");
        } else {
            // 插入数据
            UserInfo userInfo = new UserInfo();
            userInfo.setUserInfoUsername(userRegisterBO.getAccount());
            userInfo.setUserInfoPassword(CommonUtils.MD5(userRegisterBO.getPassword1()));
            userInfo.setCreateTime(new Date());
            userInfo.setUpdateTime(new Date());
            userInfo.setUserInfoEnable(1);
            userInfo.setUserInfoHeadImgUrl(BaseHeadImagesUtils.getRandomHeadImage());
            userInfoService.insert(userInfo);
            return JsonData.builderSuccess();
        }
    }

    /**
     * 判断对象是否全不为空
     *
     * @param userRegisterBO 需要判断的对象
     * @return 返回判断的结果
     */
    private boolean isAllNotNull(UserRegisterBO userRegisterBO) {
        // 判断非空 非空格
        String account = userRegisterBO.getAccount();
        String password1 = userRegisterBO.getPassword1();
        String password2 = userRegisterBO.getPassword2();
        String code = userRegisterBO.getCode();
        if (null == account ||
                null == password1 ||
                null == password2 ||
                null == code) {
            return false;
        }
        if (account.trim().length() == 0 || password1.trim().length() == 0 || password2.trim().length() == 0 || code.trim().length() == 0) {
            return false;
        }
        return true;
    }

    /**
     * 获取密码
     *
     * @param userRegisterBO 需要判断的对象
     * @return 返回密码
     */
    private String getPassword(UserRegisterBO userRegisterBO) {
        if (isAllNotNull(userRegisterBO)) {
            if (!userRegisterBO.getPassword1().equals(userRegisterBO.getPassword2())) {
                return null;
            }
        }
        return userRegisterBO.getPassword1();
    }

    /**
     * 用户根据验证码登录的接口
     *
     * @param userLoginByCodeBO 用户验证码登录BO
     * @return 返回登录的结果BO
     */
    @Override
    public JsonData loginByCodeData(UserLoginByCodeBO userLoginByCodeBO) {
        if (null == userLoginByCodeBO) {
            log.info("UserLoginServiceImpl.loginByCodeData - 数据不能为空");
            return JsonData.builderError("数据不能为空");
        }
        if (null == userLoginByCodeBO.getAccount() || userLoginByCodeBO.getAccount().trim().length() == 0) {
            log.info("UserLoginServiceImpl.loginByCodeData - 请输入有效的手机号或者邮箱");
            return JsonData.builderError("请输入有效的手机号或者邮箱");
        }
        if (null == userLoginByCodeBO.getCode() || userLoginByCodeBO.getCode().trim().length() == 0) {
            log.info("UserLoginServiceImpl.loginByCodeData - 请输入有效的验证码");
            return JsonData.builderError("请输入有效的验证码");
        }
        UserInfo userInfo = userInfoService.queryOneByUsername(userLoginByCodeBO.getAccount());
        if (null == userInfo) {
            log.info("UserLoginServiceImpl.loginByCodeData - 账户不存在");
            return JsonData.builderError("账户不存在，请注册");
        }
        String targetCode = String.valueOf(redisUtils.get(userLoginByCodeBO.getAccount()));
        log.info("UserLoginServiceImpl.loginByCodeData - code" + targetCode);
        if (null == targetCode || "null".equals(targetCode)) {
            log.info("UserLoginServiceImpl.loginByCodeData - 验证码已经失效");
            return JsonData.builderError("你的验证码已经失效");
        }
        if (!userLoginByCodeBO.getCode().equals(targetCode)) {
            log.info("UserLoginServiceImpl.loginByCodeData - 验证码不正确");
            return JsonData.builderError("验证码不正确");
        } else {
            log.info("UserLoginServiceImpl.loginByCodeData - 验证成功，登录成功");
            // 把用户信息存储到 Token 中
            String token = JWTUtils.generateJWTWebToken(userInfo);
            return JsonData.builderSuccess(token, "成功");
        }
    }

    /**
     * 用户修改密码
     *
     * @param userResetPwdBO 需要修改的对象
     * @return 返回修修改的结果
     */
    @Override
    public JsonData resetPassword(UserResetPwdBO userResetPwdBO) {
        String password = getPassword(userResetPwdBO);
        if (null == password) {
            log.info("UserLoginServiceImpl.resetPassword - 密码不正确");
            return JsonData.builderError("密码不正确");
        }
        // 从Redis获取code
        String targetCode = redisUtils.get(userResetPwdBO.getAccount()).toString();
        if (null == targetCode) {
            log.info("UserLoginServiceImpl.resetPassword - 验证码失效，请重新发送");
            return JsonData.builderError("验证码失效，请重新发送");
        }
        System.out.println(targetCode);
        System.out.println(userResetPwdBO.getCode());
        if (!targetCode.equals(userResetPwdBO.getCode())) {
            log.info("UserLoginServiceImpl.resetPassword - 验证码错误");
            return JsonData.builderError("验证码错误");
        }
        UserInfo userInfo = userInfoService.queryOneByUsername(userResetPwdBO.getAccount());
        if (null == userInfo) {
            log.info("UserLoginServiceImpl.resetPassword - 用户不存在，请先注册");
            return JsonData.builderError("用户不存在，请先注册");
        }
        userInfo.setUserInfoPassword(CommonUtils.MD5(password));
        userInfo.setUpdateTime(new Date());
        userInfoService.update(userInfo);
        log.info("UserLoginServiceImpl.resetPassword - 修改密码成功");
        return JsonData.builderSuccess(null, "修改成功");
    }


    /**
     * 判断对象是否全不为空
     *
     * @param userResetPwdBO 需要判断的对象
     * @return 返回判断的结果
     */
    private boolean isAllNotNull(UserResetPwdBO userResetPwdBO) {
        // 判断非空 非空格
        String account = userResetPwdBO.getAccount();
        String password1 = userResetPwdBO.getPassword1();
        String password2 = userResetPwdBO.getPassword2();
        String code = userResetPwdBO.getCode();
        if (null == account ||
                null == password1 ||
                null == password2 ||
                null == code) {
            return false;
        }
        if (account.trim().length() == 0 || password1.trim().length() == 0 || password2.trim().length() == 0 || code.trim().length() == 0) {
            return false;
        }
        return true;
    }

    /**
     * 获取密码
     *
     * @param userResetPwdBO 需要判断的对象
     * @return 返回密码
     */
    private String getPassword(UserResetPwdBO userResetPwdBO) {
        if (isAllNotNull(userResetPwdBO)) {
            if (!userResetPwdBO.getPassword1().equals(userResetPwdBO.getPassword2())) {
                return null;
            }
        }
        return userResetPwdBO.getPassword1();
    }
}
